package com.mrxu.monitor.util;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.ArrayList;
import java.util.List;


public class CommonUtil {

    private CommonUtil(){}

    /**
     * 正则匹配类
     */
    public static PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 路径是否匹配
     * @param pathPattern 正则
     * @param requestPath 请求路径
     * @return 结果
     */
    public static boolean matchPath(String pathPattern,String requestPath){
        if(pathPattern == null){
            return false;
        }
        if(requestPath.equalsIgnoreCase(pathPattern)){
            return true;
        }
        return pathMatcher.match(pathPattern,requestPath);
    }

    /**
     * 路径是否匹配
     * @param pathPatterns 正则
     * @param requestPath 请求路径
     * @return 结果
     */
    public static boolean matchPath(List<String> pathPatterns, String requestPath){
        if(pathPatterns == null || pathPatterns.isEmpty()){
            return false;
        }
        for (String pathPattern : pathPatterns) {
            if(matchPath(pathPattern,requestPath)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String pattern = "/**/*.js";
        System.out.println(matchPath(pattern,"/hello/wor/a.js"));
        String ip = "127.0.0.1";
        List<String> ips = new ArrayList<>();
        ips.add("127.0.0.1");
        ips.add("192.168.1.1");
        System.out.println(matchPath(ip,"127.0.0.1"));
        System.out.println(matchPath(ips,"192.168.1.1"));
        System.out.println(matchPath(ips,"192.168.1.2"));
    }
}
